<template>
  <div class="message-notification">
    <!-- 消息卡片 -->
    <el-card class="message-card" v-if="showMessages">
      <template #header>
        <div class="message-header">
          <div class="header-left">
            <el-icon><Bell /></el-icon>
            <span class="title">重要消息</span>
            <el-badge 
              v-if="unreadCount > 0" 
              :value="unreadCount" 
              class="unread-badge"
            />
          </div>
          <div class="header-right">
            <el-button 
              v-if="messages.length > 0"
              text 
              size="small" 
              @click="markAllRead"
              :loading="markingAllRead"
            >
              全部已读
            </el-button>
            <el-button 
              text 
              size="small" 
              @click="toggleCollapse"
            >
              {{ collapsed ? '展开' : '收起' }}
              <el-icon>
                <ArrowUp v-if="!collapsed" />
                <ArrowDown v-if="collapsed" />
              </el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <!-- 消息列表 -->
      <div v-show="!collapsed" class="message-list">
        <div 
          v-for="message in displayMessages" 
          :key="message.id"
          class="message-item"
          :class="[
            `message-${message.priority}`,
            { 'message-read': message.is_read }
          ]"
        >
          <div class="message-content">
            <div class="message-meta">
              <span 
                class="priority-tag" 
                :class="`priority-${message.priority}`"
              >
                {{ getPriorityIcon(message.priority) }}
                {{ message.priority_display }}
              </span>
              <span class="message-time">{{ formatTime(message.created_at) }}</span>
            </div>
            <h4 class="message-title">{{ message.title }}</h4>
            <p class="message-preview">{{ getPreview(message.content) }}</p>
          </div>
          <div class="message-actions">
            <el-button 
              text 
              size="small" 
              @click="viewDetail(message)"
            >
              查看详情
            </el-button>
            <el-button 
              v-if="!message.is_read"
              text 
              size="small" 
              @click="markRead(message)"
              :loading="markingRead[message.id]"
            >
              已读
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="messages.length === 0" class="empty-state">
          <el-icon size="48" color="#dcdfe6"><DocumentRemove /></el-icon>
          <p>暂无消息</p>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more">
          <el-button text @click="loadMore" :loading="loading">
            加载更多消息
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 消息详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      :title="selectedMessage?.title"
      width="600px"
      append-to-body
      :z-index="3000"
      @close="closeDetail"
    >
      <div v-if="selectedMessage" class="message-detail">
        <div class="detail-meta">
          <span 
            class="priority-tag" 
            :class="`priority-${selectedMessage.priority}`"
          >
            {{ getPriorityIcon(selectedMessage.priority) }}
            {{ selectedMessage.priority_display }}
          </span>
          <span class="detail-time">{{ formatTime(selectedMessage.created_at) }}</span>
        </div>
        <div class="detail-content" v-html="selectedMessage.content"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDetail">关闭</el-button>
          <el-button 
            v-if="selectedMessage && !selectedMessage.is_read"
            type="primary" 
            @click="markRead(selectedMessage)"
            :loading="markingRead[selectedMessage.id]"
          >
            标记已读
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Bell, ArrowUp, ArrowDown, DocumentRemove } from '@element-plus/icons-vue'
import { messageApi } from '@/api/message'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// 响应式数据
const messages = ref([])
const unreadCount = ref(0)
const loading = ref(false)
const collapsed = ref(false)
const showMessages = ref(true)
const hasMore = ref(false)
const currentPage = ref(1)
const markingAllRead = ref(false)
const markingRead = reactive({})

// 消息详情弹窗
const detailVisible = ref(false)
const selectedMessage = ref(null)

// 计算属性
const displayMessages = computed(() => {
  return messages.value.slice(0, 5) // 只显示最新5条
})

// 方法
const loadMessages = async (page = 1) => {
  try {
    loading.value = true
    const response = await messageApi.getUserMessages({
      page,
      page_size: 5,
      ordering: '-created_at'
    })
    
    if (page === 1) {
      messages.value = response.data.results
      // 如果是首次加载，根据消息状态决定是否收起
      if (messages.value.length === 0) {
        // 没有消息时，默认收起
        collapsed.value = true
      } else {
        // 有消息时，检查是否有未读消息
        const hasUnreadMessages = messages.value.some(msg => !msg.is_read)
        if (!hasUnreadMessages) {
          // 所有消息都已读，默认收起
          collapsed.value = true
        }
        // 如果有未读消息，保持展开状态（collapsed.value默认为false）
      }
    } else {
      messages.value.push(...response.data.results)
    }
    
    hasMore.value = !!response.data.next
    currentPage.value = page
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  } finally {
    loading.value = false
  }
}

const loadUnreadCount = async () => {
  try {
    const response = await messageApi.getUnreadCount()
    unreadCount.value = response.data.unread_count
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

const loadMore = () => {
  if (!loading.value && hasMore.value) {
    loadMessages(currentPage.value + 1)
  }
}

const markRead = async (message) => {
  if (message.is_read) return
  
  try {
    markingRead[message.id] = true
    await messageApi.markMessageRead(message.id)
    
    message.is_read = true
    unreadCount.value = Math.max(0, unreadCount.value - 1)
    
    ElMessage.success('已标记为已读')
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  } finally {
    markingRead[message.id] = false
  }
}

const markAllRead = async () => {
  try {
    markingAllRead.value = true
    await messageApi.markAllMessagesRead()
    
    // 更新本地状态
    messages.value.forEach(msg => {
      msg.is_read = true
    })
    unreadCount.value = 0
    
    // 全部已读后自动收起
    collapsed.value = true
    
    ElMessage.success('已标记全部为已读')
  } catch (error) {
    console.error('批量标记已读失败:', error)
    ElMessage.error('批量标记已读失败')
  } finally {
    markingAllRead.value = false
  }
}

const viewDetail = async (message) => {
  selectedMessage.value = message
  detailVisible.value = true
  
  // 如果未读，自动标记为已读
  if (!message.is_read) {
    await markRead(message)
  }
}

const closeDetail = () => {
  detailVisible.value = false
  selectedMessage.value = null
}

const toggleCollapse = () => {
  collapsed.value = !collapsed.value
}

const getPriorityIcon = (priority) => {
  const icons = {
    urgent: '🚨',
    important: '⚠️',
    normal: 'ℹ️'
  }
  return icons[priority] || 'ℹ️'
}

const getPreview = (content) => {
  // 移除HTML标签并截取前50个字符
  const text = content.replace(/<[^>]*>/g, '')
  return text.length > 50 ? text.substring(0, 50) + '...' : text
}

const formatTime = (dateString) => {
  const date = new Date(dateString)
  return formatDistanceToNow(date, { 
    addSuffix: true, 
    locale: zhCN 
  })
}

// 定时刷新未读数量
let refreshTimer = null
const startRefreshTimer = () => {
  refreshTimer = setInterval(() => {
    loadUnreadCount()
  }, 30000) // 30秒刷新一次
}

const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 生命周期
onMounted(() => {
  loadMessages()
  loadUnreadCount()
  startRefreshTimer()
})

onUnmounted(() => {
  stopRefreshTimer()
})

// 暴露给父组件的方法
defineExpose({
  refresh: () => {
    loadMessages()
    loadUnreadCount()
  },
  getUnreadCount: () => unreadCount.value
})
</script>

<style scoped>
.message-notification {
  margin-bottom: 20px;
}

.message-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title {
  font-weight: 600;
  color: #303133;
}

.unread-badge {
  margin-left: 4px;
}

.header-right {
  display: flex;
  gap: 8px;
}

.message-list {
  max-height: 400px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 6px;
  border-left: 4px solid transparent;
  background-color: #fafafa;
  transition: all 0.3s;
}

.message-item:hover {
  background-color: #f0f0f0;
}

.message-urgent {
  border-left-color: #f56c6c;
  background-color: #fef0f0;
}

.message-important {
  border-left-color: #e6a23c;
  background-color: #fdf6ec;
}

.message-normal {
  border-left-color: #409eff;
  background-color: #ecf5ff;
}

.message-read {
  opacity: 0.7;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 4px;
}

.priority-tag {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  white-space: nowrap;
}

.priority-urgent {
  background-color: #f56c6c;
  color: white;
}

.priority-important {
  background-color: #e6a23c;
  color: white;
}

.priority-normal {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-title {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.message-preview {
  margin: 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

.message-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-left: 12px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.load-more {
  text-align: center;
  padding: 16px;
}

/* 消息详情 */
.message-detail {
  padding: 16px 0;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.detail-time {
  font-size: 13px;
  color: #909399;
}

.detail-content {
  line-height: 1.6;
  color: #303133;
}

.detail-content p {
  margin-bottom: 12px;
}

.detail-content:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}
</style>